﻿using DzInfo.Tools;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.FIN.App.Core;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.SerivesPlugin.ZhuMuNiao
{
    [Description("啄木鸟发货通知单审核、反审核时更新已发货金额"), HotUpdate]
    public class fhAutoOperation : AbstractOperationServicePlugIn
    {
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            var obj = e.DataEntitys.FirstOrDefault();
            if (obj == null) { return; }
            var skmx = obj["POSW_Cust_Entry100002"] as DynamicObjectCollection;
            //skmx = (DynamicObjectCollection)skmx.Where(w => !w["F_POSW_Text_dvn"].IsNullOrEmptyOrWhiteSpace());
            var skmx2 = skmx.Where(w => !w["F_POSW_Text_dvn"].IsNullOrEmptyOrWhiteSpace());
            decimal kfhje = Convert.ToDecimal(obj["F_POSW_KYQty2"]);
            string opNumber = this.FormOperation.Operation;
            if (opNumber.Equals("Save"))
            {
                //未审核发货通知单
                DynamicObjectCollection xd = Getxd();
                //清空已选单发货金额
                DynamicObjectCollection yxdzcc = GetYxdZcc();
                //清空已使用发货金额
                DynamicObjectCollection yxdwsy = GetYxdWsy();
                //已审核发货通知单
                DynamicObjectCollection audits = GetAudits();

                if (xd.Count > 0)
                {
                    foreach (var x in xd)
                    {
                        UpdateFHXD(x);
                        UpdateCYJE(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHXDZERO(x);
                        }
                    }
                }

                if (audits.Count > 0)
                {
                    foreach (var x in audits)
                    {
                        UpdateFHSH(x);
                        UpdateCYJE(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHSYZERO(x);
                        }
                    }
                }
                if (yxdwsy.Count > 0)
                {
                    foreach (var x in yxdwsy)
                    {
                        SetFHSYZERO(x);
                        UpdateCYJE(x);
                    }
                }
                if (yxdzcc.Count > 0)
                {
                    foreach (var x in yxdzcc)
                    {
                        SetZCC(x);
                        UpdateCYJE(x);
                    }
                }
            }
            if (opNumber.Equals("Submit"))
            {
                //未审核发货通知单
                DynamicObjectCollection xd = Getxd();
                //清空已选单发货金额
                DynamicObjectCollection yxdzcc = GetYxdZcc();
                //清空已使用发货金额
                DynamicObjectCollection yxdwsy = GetYxdWsy();
                //已审核发货通知单
                DynamicObjectCollection audits = GetAudits();

                if (xd.Count > 0)
                {
                    foreach (var x in xd)
                    {
                        UpdateFHXD(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHXDZERO(x);
                        }
                    }
                }

                if (audits.Count > 0)
                {
                    foreach (var x in audits)
                    {
                        UpdateFHSH(x);
                        UpdateCYJE(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHSYZERO(x);
                        }
                    }
                }
                if (yxdwsy.Count > 0)
                {
                    foreach (var x in yxdwsy)
                    {
                        SetFHSYZERO(x);
                        UpdateCYJE(x);
                    }
                }
                if (yxdzcc.Count > 0)
                {
                    foreach (var x in yxdzcc)
                    {
                        SetZCC(x);
                        UpdateCYJE(x);
                    }
                }
            }
            if (opNumber.Equals("UnAudit"))
            {
                if (skmx2.Count() > 0)
                {
                    foreach (var x in skmx2)
                    {
                        //把收款单剩余收款金额加回去
                        decimal je = Convert.ToDecimal(x["FActRecAmount"]);
                        string dh = x["F_POSW_Text_dvn"].ToString();
                        UpdateSKDCYSKJE(dh, je);
                    }
                }
                //未审核发货通知单
                DynamicObjectCollection xd = Getxd();
                //清空已选单发货金额
                DynamicObjectCollection yxdzcc = GetYxdZcc();
                //清空已使用发货金额
                DynamicObjectCollection yxdwsy = GetYxdWsy();
                //已审核发货通知单
                DynamicObjectCollection audits = GetAudits();

                if (xd.Count > 0)
                {
                    foreach (var x in xd)
                    {
                        UpdateFHXD(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHXDZERO(x);
                        }
                    }
                }

                if (audits.Count > 0)
                {
                    foreach (var x in audits)
                    {
                        UpdateFHSH(x);
                        UpdateCYJE(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHSYZERO(x);
                        }
                    }
                }
                if (yxdwsy.Count > 0)
                {
                    foreach (var x in yxdwsy)
                    {
                        SetFHSYZERO(x);
                        //UpdateCYJE(x);
                    }
                }
                if (yxdzcc.Count > 0)
                {
                    foreach (var x in yxdzcc)
                    {
                        SetZCC(x);
                        //UpdateCYJE(x);
                    }
                }
            }
            if (opNumber.Equals("Audit"))
            {
                //未审核发货通知单
                DynamicObjectCollection xd = Getxd();
                //清空已选单发货金额
                DynamicObjectCollection yxdzcc = GetYxdZcc();
                //清空已使用发货金额
                DynamicObjectCollection yxdwsy = GetYxdWsy();
                //已审核发货通知单
                DynamicObjectCollection audits = GetAudits();

                if (xd.Count > 0)
                {
                    foreach (var x in xd)
                    {
                        UpdateFHXD(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHXDZERO(x);
                        }
                    }
                }

                if (audits.Count > 0)
                {
                    foreach (var x in audits)
                    {
                        UpdateFHSH(x);
                        UpdateCYJE(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHSYZERO(x);
                        }
                    }
                }
                if (yxdwsy.Count > 0)
                {
                    foreach (var x in yxdwsy)
                    {
                        SetFHSYZERO(x);
                        UpdateCYJE(x);
                    }
                }
                if (yxdzcc.Count > 0)
                {
                    foreach (var x in yxdzcc)
                    {
                        SetZCC(x);
                        UpdateCYJE(x);
                    }
                }
            }
            if (opNumber.Equals("Delete"))
            {
                //未审核发货通知单
                DynamicObjectCollection xd = Getxd();
                //清空已选单发货金额
                DynamicObjectCollection yxdzcc = GetYxdZcc();
                //清空已使用发货金额
                DynamicObjectCollection yxdwsy = GetYxdWsy();
                //已审核发货通知单
                DynamicObjectCollection audits = GetAudits();

                if (xd.Count > 0)
                {
                    foreach (var x in xd)
                    {
                        UpdateFHXD(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHXDZERO(x);
                        }
                    }
                }

                if (audits.Count > 0)
                {
                    foreach (var x in audits)
                    {
                        UpdateFHSH(x);
                        UpdateCYJE(x);
                    }
                }
                else
                {
                    DynamicObjectCollection rows = GetFHRows();
                    if (rows.Count > 0)
                    {
                        foreach (var x in rows)
                        {
                            SetFHSYZERO(x);
                        }
                    }
                }
                if (yxdwsy.Count > 0)
                {
                    foreach (var x in yxdwsy)
                    {
                        SetFHSYZERO(x);
                        UpdateCYJE(x);
                    }
                }
                if (yxdzcc.Count > 0)
                {
                    foreach (var x in yxdzcc)
                    {
                        SetZCC(x);
                        UpdateCYJE(x);
                    }
                }
            }
        }

        private void UpdateSKDCYSKJE(string dh, decimal je)
        {
            string sql = string.Format(@"/*dialect*/  UPDATE T0 SET T0.F_ZMN_SSYSKJE=T0.F_ZMN_SSYSKJE+{0} FROM T_AR_RECEIVEBILL T0 WHERE T0.FBILLNO='{1}' ", je, dh);
            DBUtils.Execute(this.Context, sql);
        }

        private void SetZCC(DynamicObject x)
        {
            string billno = x["DH"].ToString();
            string sql = string.Format(@"/*dialect*/  UPDATE T0 SET T0.F_ZMN_FHXDJE=0 FROM T_AR_RECEIVEBILL T0 WHERE T0.FBILLNO='{0}' ", billno);
            DBUtils.Execute(this.Context, sql);
        }

        private DynamicObjectCollection GetYxdZcc()
        {
            string sql = "";
            sql = string.Format(@"/*dialect*/ 
            SELECT T0.FBILLNO DH FROM T_AR_RECEIVEBILL T0
            WHERE T0.F_ZMN_FHXDJE>0 AND T0.FBILLNO NOT IN (

            SELECT DISTINCT T1.F_POSW_TEXT_DVN
            FROM T_SAL_DELIVERYNOTICE T0
            JOIN POSW_t_Cust_Entry100002 T1 ON T1.FID=T0.FID
            WHERE T1.F_POSW_TEXT_DVN<>'' AND T0.FDOCUMENTSTATUS<>'C') ");
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        private DynamicObjectCollection GetYxdWsy()
        {
            string sql = "";
            sql = string.Format(@"/*dialect*/ 
            SELECT T0.FBILLNO DH FROM T_AR_RECEIVEBILL T0
            WHERE T0.F_ZMN_FHSYJE>0 AND T0.FBILLNO NOT IN (

            SELECT DISTINCT T1.F_POSW_TEXT_DVN
            FROM T_SAL_DELIVERYNOTICE T0
            JOIN POSW_t_Cust_Entry100002 T1 ON T1.FID=T0.FID
            WHERE T1.F_POSW_TEXT_DVN<>'' AND T0.FDOCUMENTSTATUS='C' ) ");
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        private void SetFHSYZERO(DynamicObject x)
        {
            string billno = x["DH"].ToString();
            string sql = string.Format(@"/*dialect*/  UPDATE T0 SET T0.F_ZMN_FHSYJE=0 FROM T_AR_RECEIVEBILL T0 WHERE T0.FBILLNO='{0}' ", billno);
            DBUtils.Execute(this.Context, sql);
        }

        private DynamicObjectCollection GetFHRows()
        {
            string sql = "";
            sql = string.Format(@"/*dialect*/ 
            SELECT T0.F_POSW_TEXT_DVN DH FROM POSW_t_Cust_Entry100002 T0 WHERE T0.F_POSW_TEXT_DVN<>'' ");
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        private void SetFHXDZERO(DynamicObject x)
        {
            string billno = x["DH"].ToString();
            string sql = string.Format(@"/*dialect*/  UPDATE T0 SET T0.F_ZMN_FHXDJE=0,T0.F_ZMN_FHSYJE=0 FROM T_AR_RECEIVEBILL T0 WHERE T0.FBILLNO='{0}' ", billno);
            DBUtils.Execute(this.Context, sql);
        }

        private void UpdateCYJE(DynamicObject x)
        {
            string billno = x["DH"].ToString();
            string sql = string.Format(@"/*dialect*/  UPDATE T0 SET T0.F_ZMN_SSYSKJE=T0.FREALRECAMOUNTFOR-T0.F_ZMN_XDSYJE-T0.F_ZMN_SYSKJE-T0.F_zmn_fhxdje-T0.F_zmn_fhsyje FROM T_AR_RECEIVEBILL T0 WHERE T0.FBILLNO='{0}' ", billno);
            DBUtils.Execute(this.Context, sql);
        }

        /// <summary>
        /// 更新发货使用金额
        /// </summary>
        /// <param name="x"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void UpdateFHSH(DynamicObject x)
        {
            decimal je = Convert.ToDecimal(x["JE"]);
            string billno = x["DH"].ToString();
            string sql = string.Format(@"/*dialect*/  UPDATE T0 SET T0.F_zmn_fhsyje={0} FROM T_AR_RECEIVEBILL T0 WHERE T0.FBILLNO='{1}' ", je, billno);
            DBUtils.Execute(this.Context, sql);
        }

        /// <summary>
        /// 已审核的发货通知单
        /// </summary>
        /// <returns></returns>
        private DynamicObjectCollection GetAudits()
        {
            string sql = "";
            sql = string.Format(@"/*dialect*/ 
            SELECT SUM(T1.FACTRECAMOUNT) JE,T1.F_POSW_TEXT_DVN DH
            FROM T_SAL_DELIVERYNOTICE T0
            JOIN POSW_t_Cust_Entry100002 T1 ON T1.FID=T0.FID
            WHERE T1.F_POSW_TEXT_DVN<>'' AND T0.FDOCUMENTSTATUS='C' AND T1.F_zmn_xsddh=''
            GROUP BY T1.F_POSW_TEXT_DVN ");
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        /// <summary>
        /// 更新收款单发货选单金额
        /// </summary>
        /// <param name="x"></param>
        private void UpdateFHXD(DynamicObject x)
        {
            decimal je = Convert.ToDecimal(x["JE"]);
            string billno = x["DH"].ToString();
            string sql = string.Format(@"/*dialect*/  UPDATE T0 SET T0.F_zmn_fhxdje={0} FROM T_AR_RECEIVEBILL T0 WHERE T0.FBILLNO='{1}' ", je, billno);
            DBUtils.Execute(this.Context, sql);
        }

        /// <summary>
        /// 发货通知单选单金额
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private DynamicObjectCollection Getxd()
        {
            string sql = "";
            sql = string.Format(@"/*dialect*/ 
            SELECT SUM(T1.FACTRECAMOUNT) JE,T1.F_POSW_TEXT_DVN DH
            FROM T_SAL_DELIVERYNOTICE T0
            JOIN POSW_t_Cust_Entry100002 T1 ON T1.FID=T0.FID
            WHERE T1.F_POSW_TEXT_DVN<>'' AND T0.FDOCUMENTSTATUS<>'C' AND T1.F_zmn_xsddh=''
            GROUP BY T1.F_POSW_TEXT_DVN ");
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        private void UpSkfhje(string skBillno, decimal sumJe)
        {
            string sql = string.Format(@"/*dialect*/  update t0 set t0.F_ZMN_YFHJE={0} from T_AR_RECEIVEBILL t0 where t0.FBILLNO='{1}' ", sumJe, skBillno);
            DBUtils.Execute(this.Context, sql);
        }

        private decimal GetFHJE(string skBillno, string opNumber)
        {
            List<string> list = new List<string>();
            string sql = "";
            if (opNumber == "Save")
            {

            }

            sql = string.Format(@"/*dialect*/ 
                SELECT T1.FACTRECAMOUNT FROM T_SAL_DELIVERYNOTICE T0
                JOIN POSW_t_Cust_Entry100002 T1 ON T1.FID=T0.FID
                where  T1.F_POSW_TEXT_DVN='{0}' ", skBillno);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }

        //public override void EndOperationTransaction(EndOperationTransactionArgs e)
        //{
        //    base.EndOperationTransaction(e);
        //    var obj = e.DataEntitys.FirstOrDefault();
        //    bool isCP = Convert.ToBoolean(obj["F_POSW_CheckBox_4d0"]);
        //    if (!isCP)
        //    {
        //        var ids = e.DataEntitys.Select(s => s["id"]).ToArray();
        //        var res = AppServiceContext.SubmitService.Submit(this.Context, this.BusinessInfo, ids, "Submit", null);
        //        this.OperationResult.MergeResult(res);
        //        if (res.IsSuccess)
        //        {
        //            this.OperationResult.MergeResult(AppServiceContext.AuditService.Audit(this.Context, this.BusinessInfo, ids, OperateOption.Create()));
        //        }
        //    }
        //}
        //public override void BeginOperationTransaction(BeginOperationTransactionArgs e)
        //{
        //    base.BeginOperationTransaction(e);
        //    var obj = e.DataEntitys.FirstOrDefault();
        //    //比较预收金额和发货金额
        //    decimal fh = GetFH(obj);
        //    decimal ys = GetYS(obj);
        //    if (fh <= ys)
        //    {
        //        //标识审批标识为否
        //        SetStatues(obj, 0);
        //        //自动审核
        //    }
        //    else
        //    {
        //        //标识审批标识为是
        //        SetStatues(obj, 1);
        //    }
        //}
        /// <summary>
        /// 标识审批标识
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="v"></param>
        private void SetStatues(DynamicObject obj, int v)
        {
            IBillView val = KingdeeTools.CreateBillView(this.Context, this.BusinessInfo.GetForm().Id);
            val.Model.DataObject = obj;
            val.Model.SetValue("F_POSW_CheckBox_4d0", v, 0);
        }

        /// <summary>
        /// 预收金额
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private decimal GetYS(DynamicObject obj)
        {
            decimal ys = 0;
            var ysObj = obj["POSW_Cust_Entry100002"] as DynamicObjectCollection;
            ys = ysObj.Select(s => s["FActRecAmount"]).Sum(p => Convert.ToDecimal(p));
            return ys;
        }
        /// <summary>
        /// 发货金额
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private decimal GetFH(DynamicObject obj)
        {
            decimal fh = 0;
            var finObj = obj["SAL_DELIVERYNOTICEFIN"] as DynamicObjectCollection;
            fh = Convert.ToDecimal(finObj[0]["BillAllAmount"]);
            return fh;
        }

        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
    }
}
